`define DISABLE_SPI_SHARED_DEVICES SPI_SS_B <= 1; AMP_CS <= 1; AD_COV <= 0; SF_CE0 <=1; FPGA_INIT_B <=1; 
`define DECLARE_SPI_SHARED_DEVICES reg SPI_SS_B; reg AMP_CS; reg AD_COV;reg SF_CE0; reg FPGA_INIT_B;
  
`define STATE_IDLE 		0
`define STATE_LOAD 		1
`define STATE_SEND		2
//`define STATE_3RD_BYTE 	3
//`define STATE_4TH_BYTE 	4


module DACDriver( wClk, wRst, wValue, wStart, rReady);
input wClk;
input wRst;
input [11:0] wValue;
input wStart;
output rReady;

`DECLARE_SPI_SHARED_DEVICES
reg rReady;
reg rStart_Latch;
reg [1:0] rBytesSent;
reg [2:0] rState;
reg [7:0] rSPI_ToData;
wire [7:0] wSPI_FromData;
wire wSPI_DataReady;
wire wSPI_MOSI;
wire wSPI_MISO;
wire wSPI_SS;
wire wSPI_SPCLK;
reg rSPI_Start;
reg rSPI_TransactionActive;
reg [31:0] rDAC_COMMAND;

/* initialization of signals */
initial begin
	`DISABLE_SPI_SHARED_DEVICES
	rReady <= 0;  /* Initialize variable as not ready */
	rStart_Latch <= 0;
	rBytesSent <= 0;
	rDAC_COMMAND <= 0;
	rSPI_Start <=0;
	rSPI_TransactionActive<=0;
	rSPI_ToData <= 0;
	rState <= `STATE_IDLE;
end

always @(posedge wClk)
begin 
	/* Restore output transition signals to default value */
	rSPI_Start <= 0;
	
	/* Start Condition detection */
	rStart_Latch <= (rState == `STATE_IDLE)? wStart: 0;
	//if (wStart == 1)	rStart_Latch <= 1;

	/* Main State Machine */
	case (rState) 
	`STATE_IDLE: 
	begin 
		rReady <= 1;
		if (rStart_Latch == 1)	
		begin 
			rSPI_Start <= 1;
			rState <= `STATE_LOAD;
			rDAC_COMMAND[31:16]<= 16'h003F;
			rDAC_COMMAND[15:4] <= wValue;
			rDAC_COMMAND[3:0]  <=  4'h0;
			rStart_Latch <= 0;
			rBytesSent <= 0;
			rSPI_TransactionActive <= 1;
			rReady <= 0;
		end
		else 
		begin
			rSPI_TransactionActive <= 0;
		end			
	end
	`STATE_LOAD:
	begin
		if (rBytesSent == 0) rSPI_ToData <= rDAC_COMMAND[7:0];
		if (rBytesSent == 1) rSPI_ToData <= rDAC_COMMAND[15:8];
		if (rBytesSent == 2) rSPI_ToData <= rDAC_COMMAND[23:16];
		if (rBytesSent == 3) rSPI_ToData <= rDAC_COMMAND[31:24];
		rBytesSent <= rBytesSent + 1;
		rSPI_Start <= 1;
		rState <= `STATE_SEND;
	end
	`STATE_SEND:
	begin
		if (wSPI_DataReady == 1)
		begin
			rState <= `STATE_LOAD;
			if (rBytesSent == 0) begin
				rState <= `STATE_IDLE;
				rSPI_Start <= 0;
				rReady <= 1;				
			end
		end
	end
	endcase
end

SPI_Module SPI(
.A_CLK					(wClk),
.A_RST					(wRst),
.B_DATAPAR_MOSI			(rSPI_ToData),
.B_DATAPAR_MISO			(wSPI_FromData),
.B_START				(rSPI_Start),
.B_DATA_READY			(wSPI_DataReady),
.B_TRANSACTION_ACTIVE	(rSPI_TransactionActive),
.C_MOSI					(wSPI_MOSI),
.C_MISO					(wSPI_MISO),
.C_SS					(wSPI_SS),
.C_SPCLK				(wSPI_SPCLK));



	
endmodule
